<?php
namespace app\admin\model;

use think\Model;
use traits\model\SoftDelete;
use \app\admin\model\Syslog;

class Ad extends Model
{
    use SoftDelete;
    protected $deleteTime = 'deltime';

    /*
        多图广告修改器
    */
    public function setPicarrAttr($value)
    {
        return implode(',',$value);
    }
    /*
        读取分页
    */
    static public function Page($pagesize,$kw)
    {   
        $where=[];
        if($kw!=""){
            $where[]="(`aid` like '%$kw%' OR `title` like '%$kw%')";
        }
        return self::where(\implode("and",$where))->order("orderid DESC")->paginate(10, false, ['query' => request()->param()]);
    }
    /*
        保存数据
    */
    static public function SaveData($data)
    {   
        $id=$data['id']??0;
        
        unset($data['id']);
        $data['posttime']=time();
        //需要使用修改器的，用save方法
        $Ad=new Ad;
        if($id>0){
            Syslog::Rec(1,"更新广告[".$data['aid']."]",0);
            return $Ad->save($data,['id'=>$id]);
        }else{
            Syslog::Rec(1,"创建了广告[".$data['aid']."]",0);
            return $Ad->save($data);
        }
    }
    /*
        排序
    */
    static public function Sort($data)
    {
        $Ad=new Ad;
        foreach($data['field_ids'] as $k=>$v){
            $list[]=['id'=>$v,'orderid'=>$data['orderid_ipt'][$k]];
        }
        Syslog::Rec(1,"更新了广告排序",0);
        return $Ad->isUpdate()->saveAll($list);
    }
    /*
        批量操作(删除、启用、禁用、...)
    */
    static public function Bat($data)
    {
        $type='bat_'.$data['type'];
        $ids=\implode(',',array_unique(array_filter(\explode(',',$data['ids']))));
        return self::$type($ids);
    }
    /*
        批量启用 status:0 启用 1:禁用
    */
    static public function bat_enable($ids)
    {
        Syslog::Rec(1,"批量启用广告[$ids]",0);
        return self::where("`id` IN ($ids)")->update(['status'=>0]);
    }
    /*
        批量禁用 status:0 启用 1:禁用
    */
    static public function bat_disable($ids)
    {
        Syslog::Rec(1,"批量禁用广告[$ids]",0);
        return self::where("`id` IN ($ids)")->update(['status'=>1]);
    }
    /*
        批量删除
    */
    static public function bat_del($ids)
    {
        $Ad=new Ad;
        Syslog::Rec(1,"批量删除广告[$ids]",0);
        return $Ad->destroy($ids);
    }
}